// @/utils/storage.js
const TEMP_ORDERS_KEY = 'temp_orders'
const PAID_ORDERS_KEY = 'paid_orders'

// 获取临时订单（未支付）
export const getTempOrders = () => {
    return JSON.parse(localStorage.getItem(TEMP_ORDERS_KEY) || '[]')
}

// 获取已支付订单
export const getPaidOrders = () => {
    return JSON.parse(localStorage.getItem(PAID_ORDERS_KEY) || '[]')
}

export const saveTempOrder = (order) => {
    if (!order?.id) {
        console.error('订单ID不能为空')
        return false
    }

    try {
        const orders = getTempOrders()
        // 避免重复添加相同ID的订单
        const exists = orders.some(o => o.id === order.id)
        if (!exists) {
            orders.push(order)
            localStorage.setItem(TEMP_ORDERS_KEY, JSON.stringify(orders))
            return true
        }
        return false
    } catch (error) {
        console.error('保存订单失败:', error)
        return false
    }
}

// 标记订单为已支付
export const markOrderAsPaid = (orderId) => {
    if (!orderId) {
        console.error('订单ID不能为空')
        return false
    }

    const tempOrders = getTempOrders()
    const paidOrders = getPaidOrders()

    const orderIndex = tempOrders.findIndex(o => o.id === orderId)
    if (orderIndex === -1) {
        console.error(`未找到临时订单ID: ${orderId}`)
        return false
    }

    // 更新订单状态并移动到已支付列表
    const [paidOrder] = tempOrders.splice(orderIndex, 1)
    paidOrder.status = 'paid'
    paidOrder.paidAt = new Date().toISOString()
    paidOrders.push(paidOrder)

    // 同步到 localStorage
    localStorage.setItem(TEMP_ORDERS_KEY, JSON.stringify(tempOrders))
    localStorage.setItem(PAID_ORDERS_KEY, JSON.stringify(paidOrders))
    return true
}

